package com.heima.lock.controller;

import com.heima.lock.mapper.MtOrderMapper;
import com.heima.lock.pojos.MtOrder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * @author jack
 * @data 2023 10:09
 */
@RestController
@RequestMapping("/yy")
public class ReservationController {

    @Autowired
    private MtOrderMapper mapper;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 模拟医疗预约挂号系统  -- 基于公平锁实现
     * @param map
     * @return
     */
    @PostMapping
    public String register(@RequestBody Map<String,Object> map){
        try {
            //1. 获取参数
            String phone = String.valueOf(map.get("phone"));            //患者的手机号
            String department = String.valueOf(map.get("department"));  //预约的科室
            String doctor = String.valueOf(map.get("doctor"));          //预约的医生
            String time = String.valueOf(map.get("time"));              //预约的时间段: 2023-12-04 09.30

            //非公平锁
            //RLock lock = redissonClient.getLock(doctor);

            RLock lock = redissonClient.getFairLock(doctor);            // AQS   --> queue
            lock.lock();

            //1.1 获取当前剩余号的数量
            String residueNumStr = stringRedisTemplate.opsForValue().get("num");
            Integer residueNum = Integer.valueOf(residueNumStr);
            if (residueNum < 1){
                return "today is over , tomorrow come!";
            }


            //2. 创建一个订单数据
            MtOrder order = new MtOrder();
            order.setPhone(phone);
            order.setDepartment(department);
            order.setDoctor(doctor);
            order.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(time));
            int num = 50 - residueNum + 1;
            order.setNum( num + "");
            order.setName(Thread.currentThread().getName());
            mapper.insert(order);

            //将号的总量 - 1
            stringRedisTemplate.opsForValue().set("num",String.valueOf(--residueNum));
            lock.unlock();

            return "success :"+ num;


        }catch (Exception e){
            return "today is over , tomorrow come!";
        }


    }
}
